import requests
import os
import codecs


IP = "127.0.0.1"
PORT = "8000"
base_dir = "/data/ppocr/trainData/test/rec"
rec_path = "/data/ppocr/trainData/test/pred_ocr.txt"
tar_path = "/data/ppocr/trainData/test/fix_ocr.txt"

with codecs.open(rec_path, "a", "utf8") as f:
    with codecs.open(tar_path, "r", "utf8") as f1:
        for line in f1.readlines():
            line_split = line.strip().replace("\ufeff", "").split("\t")
            if len(line_split) != 2:
                continue
            file_name = line_split[0]
            image_path = os.path.join(base_dir, file_name)
            files = {
                "srcImage": open(image_path, "rb")
            }
            try:
                r = requests.post(url="http://{}:{}/api/v1.1/textRecognize".format(IP, PORT), files=files)
                result = r.json()
            except Exception as e:
                continue

            if result["code"] != 200:
                continue
            rec_data = result["data"]
            f.write(file_name+"\t"+rec_data+"\n")
